#!/usr/bin/php -q
<?php
//	License for all code of this IssabelPBX module can be found in the license file inside the module directory
//	Copyright 2013 Schmooze Com Inc.
//  Xavier Ourciere xourciere[at]propolys[dot]com
//

$config = parse_amportal_conf( "/etc/amportal.conf" );

require_once "phpagi.php";
require_once "phpagi-asmanager.php";

$AGI = new AGI();
debug("TTS AGI Started", 1);

$text = $argv[1];
$hash = md5($text);
$engine = $argv[2];
$enginebin = $argv[3];

if (!isset($text))
{
	return 0;
}

if ( $retval != 0 ) {
	debug("ERROR: TTS engine binary not found.", 1);
	return $retval;
}

$soundsdir = $config["ASTVARLIBDIR"]."/sounds/tts";
if( !is_dir($soundsdir) ) mkdir($soundsdir, 0775);

$wavefile = $soundsdir."/$engine-tts-$hash.wav";
debug("Generated WAV file: $wavefile", 3);
$textfile = $soundsdir."/$engine-tts-$hash.txt";
debug("TXT file: $textfile", 3);

if ( !file_exists($wavefile) ) {
	debug("Text to speech wave file doesnt exist, lets create it.", 1);
	if ( false === ($fh = fopen($textfile, "w")) ) {
		debug("ERROR: Cannot open the file: $textfile", 1);
		return 1;
	}
	if ( false === fwrite($fh, $text) ) {
		debug("ERROR: Cannot write to file: $textfile", 1);
		return 1;
	}
	fclose($fh);
	debug("Executing $engine", 1);
	switch ($engine) {
	case 'text2wave':
		exec($enginebin." -f 8000 -o $wavefile $voice $textfile");
		break;
	case 'flite':
		exec($enginebin." -f $textfile -o $wavefile");
		break;
	case 'swift':
		exec($enginebin." -p audio/channels=1,audio/sampling-rate=8000 -o $wavefile -f $textfile");
		break;
	default:
	}
}
// Adding a wait because the first time the wave file is generated, it was not played
$AGI->wait_for_digit(1000);
debug("Streaming the generated wave.", 1);
$AGI->stream_file("tts/".basename($wavefile,".wav"),'#');
debug("TTS AGI end", 1);

function parse_amportal_conf($filename) {
	$file = file($filename);
	$matches = array();
	$matchpattern = '/^\s*([a-zA-Z0-9]+)\s*=\s*(.*)\s*([;#].*)?/';
	foreach ($file as $line) {
		if (preg_match($matchpattern, $line, $matches)) {
			$conf[ $matches[1] ] = $matches[2];
		}
	}
	return $conf;
}

function debug($string, $level=3) {
	global $AGI;
	$AGI->verbose($string, $level);
}
?>
